package systempen.cmanager;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.TabActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivityTab extends TabActivity {

	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    ThemePicker.onActivityCreateSetTheme(this);
	    setContentView(R.layout.tab);
 
	    Resources res = getResources(); // Resource object to get Drawables
	    TabHost tabHost = getTabHost();  // The activity TabHost
	    TabHost.TabSpec spec;  // Resusable TabSpec for each tab
	    Intent intent;  // Reusable Intent for each tab
	    // Create an Intent to launch an Activity for the tab (to be reused)
	    intent = new Intent().setClass(this, InsertActivity.class); 
	    // Initialize a TabSpec for each tab and add it to the TabHost
	    spec = tabHost.newTabSpec("add").setIndicator("Add",
	                      res.getDrawable(R.drawable.ic_tab_insert))
	                  .setContent(intent);
	    tabHost.addTab(spec);
 
	    // Do the same for the other tabs
	    intent = new Intent().setClass(this, CostList.class);
	    spec = tabHost.newTabSpec("list").setIndicator("List",
	                      res.getDrawable(R.drawable.ic_tab_list))
	                  .setContent(intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));//neki refresh
	    tabHost.addTab(spec);
	    

	    //intent = new Intent().setClass(this, ReportList.class);
	    intent = new Intent().setClass(this, ReportActivityStack.class);
	    spec = tabHost.newTabSpec("reports").setIndicator("Reports", res.getDrawable(R.drawable.ic_tab_graph)).setContent(intent);
	    tabHost.addTab(spec);

	    intent = new Intent().setClass(this, ManageData.class);
	    spec = tabHost.newTabSpec("data").setIndicator("Backup",
	                      res.getDrawable(R.drawable.ic_tab_data)) 
	                  .setContent(intent);
	    tabHost.addTab(spec);

	    //intent = new Intent().setClass(this, BudgetList.class);
	    intent = new Intent().setClass(this, BudgetActivityStack.class);
	    spec = tabHost.newTabSpec("budget")
	    		.setIndicator("Budget",res.getDrawable(R.drawable.ic_tab_budget)) 
	            .setContent(intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
	    
	    tabHost.addTab(spec);
	    
	    
	    

	    // Ne znam kako se poziva activity za editovanje kategorija,
	    // zato sam ostavio da otvara CostList
        try{
			intent = new Intent(Intent.ACTION_VIEW);
			intent.setClassName(this, ReportGroupedList.class.getName());
			Bundle bun = new Bundle();
			bun.putString("DateFrom", util.GetDefaultFromDateDB(getApplicationContext()) );
			bun.putString("DateTo",util.GetDefaultToDateDB(getApplicationContext()));
			bun.putString("Cost", "0");
			bun.putString("Level", "0");
			intent.putExtras(bun);
        } catch(Exception ex){
        	util.showDialog(ex.getMessage().toString(), getApplicationContext());
        }

	    //intent = new Intent().setClass(this,ReportGroupedListParams.class);
        
	    spec = tabHost.newTabSpec("edit").setIndicator("Edit",
	    		this.getResources().getDrawable(R.drawable.ic_tab_edit)) 
	                  .setContent(intent);
	    tabHost.addTab(spec);
       

	    intent = new Intent().setClass(this, AccountList.class);
	    spec = tabHost.newTabSpec("account").setIndicator("Accounts",
	                      res.getDrawable(R.drawable.ic_tab_edit)) 
	                  .setContent(intent);
	    
	    TypedValue t = new TypedValue();
	    getTheme().resolveAttribute(R.attr.tabText, t, true);
	    
	    
	    for(int i=0;i<tabHost.getTabWidget().getChildCount();i++)
		{
        	tabHost.getTabWidget().getChildAt(i).setBackgroundResource(0);//(R.drawable.txt_white_bkg);
        	TextView tv = (TextView) tabHost.getTabWidget().getChildAt(i).findViewById(android.R.id.title);     
        	tv.setTextColor(getResources().getColor(t.resourceId));
		}
        
        

		Bundle bun = getIntent().getExtras();
		Integer currentTabi=0;//if param are sent then set that current tab
		if ((bun != null) && (bun.getInt("CurrentTab",0)!=0)){
			currentTabi = bun.getInt("CurrentTab",0);
		} else 
			currentTabi = 0;
		tabHost.setCurrentTab(currentTabi);
		
		//begging
		String sql;
		SharedPreferences prefs = getSharedPreferences("CMANAGER", Context.MODE_PRIVATE);
		boolean haveWeShownPreferences = prefs.getBoolean("HaveShownPrefs1.53", false);
		//haveWeShownPreferences = false;
		sql = "select count(*) as broj from log";
		if ((Integer.valueOf(util.getFirstDataString(sql, this))>10)&&(!haveWeShownPreferences))//If he has more than 10 rows inserted, and we didnt show asking
		{ 
			SharedPreferences prefs2 = getSharedPreferences("CMANAGER", Context.MODE_PRIVATE);
			SharedPreferences.Editor ed = prefs2.edit();
			ed.putBoolean("HaveShownPrefs1.53", true);
			ed.commit(); 
			AlertDialog alertDialog = new AlertDialog.Builder(this).create();
	    	alertDialog.setTitle("Buy developer a coffe:");
	    	alertDialog.setMessage("As you can see, there are no ads and only satisfaction for me are happy users.\n"+
	    				"If you like program please rate it.\n"+
	    				"If you like it alot, you can buy paid version: for now same as free. :)\n"+
	    				"Link for paid version: \n"+
	    				"https://play.google.com/store/apps/details?id=systempen.cmanager2 \n"+
	    			    "Also, I would be very happy to hear from you about what you expect from future versions.\n"+
	    			    "Please email me: lleopold@gmail.com\n"+
	    			    "Check about box for more info.\n"+
	    				//"https://market.android.com/details?id=systempen.cmanager&hl=en"
	    				"Would you like to rate Cost Manager now?"
	    			); 
	        alertDialog.setButton2("OK", new DialogInterface.OnClickListener() {
	        	public void onClick(DialogInterface dialog, int which) {
	        		//Uri uri = Uri.parse("https://market.android.com/details?id=systempen.cmanager&hl=en");
	        		Intent goToMarket = null;
	        		goToMarket = new Intent(Intent.ACTION_VIEW,Uri.parse("market://details?id=systempen.cmanager"));
	        		startActivity(goToMarket);
	        	}
	        }
	        );
	        alertDialog.setButton("Not now.", new DialogInterface.OnClickListener() {
	        	public void onClick(DialogInterface dialog, int which) {
	        	} 
	        }
	        );
	    	alertDialog.show(); 
		}
		 
	}
	

	/////////////////////////////////////////////////////////
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.menuoptionss, menu);
	    return true;
	}
	@Override
	// OVAJ SE NE KORISTI.
	// NABIJEM GA!!!
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	        case R.id.tica:
	        	startApr(this);
	        	//Toast.makeText(this, "Ja sam se ovakav rodio. A koji je tvoj izgovor?", Toast.LENGTH_LONG).show();
	            break;
	        case R.id.costs:     
	        	goManageCosts(this);//Toast.makeText(this, "Manage Costs", Toast.LENGTH_LONG).show();
	            break;
	        case R.id.reports: 
	        	//Toast.makeText(this, "Reports", Toast.LENGTH_LONG).show();
	        	goReportsList(this);
	            break;
	        case R.id.data:
	        	goDataDelete();
	        	break;
	        case R.id.themes:
	        	changeTheme(this);
	        	break;
	        case R.id.about:
	        	goAboutBox();
	        	break;
	        case R.id.accounts:
	        	goAccounts();
	        	break;

	    }
	    return true;
	}
	
	private void goAccounts() {
		try{
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setClassName(this, AccountList.class.getName());
			this.startActivity(intent);
		}catch (Exception ex){
			util.showDialog(ex.getMessage().toString(), getApplicationContext());
		}
		Toast.makeText(this, "In development", Toast.LENGTH_LONG).show();
	}


	private void changeTheme(final Activity thi) {
		final CharSequence[] items = {"Dark","Light"};//,"Sky"};
		AppPreferences app=new AppPreferences(thi);
		final int currentTeme=app.getTheme();
		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Choose theme");
		
		builder.setSingleChoiceItems(items,currentTeme, new DialogInterface.OnClickListener() {
		    public void onClick(DialogInterface dialog, int item) {
		        AppPreferences pref=new AppPreferences(thi);
		        if (items[item].equals("Dark")){
		        	pref.setTheme(ThemePicker.DARK);
		        }else if (items[item].equals("Light")){
		        	pref.setTheme(ThemePicker.LIGHT);
		        }
		        else if (items[item].equals("Sky")){
		        	pref.setTheme(ThemePicker.SKY);
		        }
		        
		        if(pref.getTheme()!=currentTeme){
			        finish();
			        Intent intent = new Intent(Intent.ACTION_VIEW);
					intent.setClassName(thi, MainActivityTab.class.getName());
					MainActivityTab.this.startActivity(intent);
		        }
		    }
		});
		AlertDialog alert = builder.create();
		alert.show();
	}

	public void goAboutBox(){
		try{
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setClassName(this, About.class.getName());
			this.startActivity(intent);
		}catch (Exception ex){
			util.showDialog(ex.getMessage().toString(), getApplicationContext());
		}
	}

	public void goDataExport(){
		try{
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setClassName(this, ManageData.class.getName());
			this.startActivity(intent);
		}catch (Exception ex){
			util.showDialog(ex.getMessage().toString(), getApplicationContext());
		}
	}
	public void goDataDelete(){
		try{
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setClassName(this, Del.class.getName());
			this.startActivity(intent);
		}catch (Exception ex){
			util.showDialog(ex.getMessage().toString(), getApplicationContext());
		}
	}
	
	public void startApr(Activity thi){
		try{
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setClassName(this, Settings.class.getName());
			this.startActivity(intent);
		}catch (Exception ex){
			util.showDialog(ex.getMessage().toString(), thi);
		}
	}

	public void goManageCosts(Activity thi){
		try{
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setClassName(thi, CostList.class.getName());
		this.startActivity(intent);
		}catch (Exception ex){
			util.showDialog(ex.getMessage().toString(), thi);
		}
	}
	
	public void goReportsList(Activity thi){
		try{
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setClassName(thi, ReportList.class.getName());
		this.startActivity(intent);
		}catch (Exception ex){
			util.showDialog(ex.getMessage().toString(), thi);
		}
	}
	public void goAccount(Activity thi){
		try{
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setClassName(thi, AccountList.class.getName());
		this.startActivity(intent);
		}catch (Exception ex){
			util.showDialog(ex.getMessage().toString(), thi);
		}
	}

}
